//
//  UIButton+Utils.m
//  ContentApp
//
//  Created by 安本超 on 2018/7/18.
//  Copyright © 2018年 翔傲科技. All rights reserved.
//

#import "UIButton+Utils.h"

@implementation UIButton (Utils)

//设置button角标
- (void)setBadge:(NSString *)number andFont:(int)font andX:(NSString *)X andY:(NSString*)Y{
    
    
    UILabel *badge = (UILabel *)[self viewWithTag:1001];
    
    if (number == nil)
    {
        [badge removeFromSuperview];
    }
    else
    {
        CGFloat width = self.bounds.size.width;
        
        CGSize size = [self getSizeOfStringWihtFont:font addMaxSize:CGSizeMake(99, 99)];
        
        if (!badge) {
            badge = [[UILabel alloc] initWithFrame:CGRectMake(width-[X intValue], [Y intValue], size.width, size.height)];
            badge.tag = 1001;
            [self addSubview:badge];
        }
        
        badge.text = number;
        
        badge.textAlignment = NSTextAlignmentCenter;
        
        badge.font = [UIFont systemFontOfSize:font];
        
        badge.backgroundColor = [UIColor redColor];
        
        badge.textColor = [UIColor whiteColor];
        
        badge.layer.cornerRadius = 4;
        
        badge.layer.masksToBounds = YES;
    }
    
    
}

-(CGSize)getSizeOfStringWihtFont:(int)fontSize addMaxSize:(CGSize)maxSize

{
    CGSize size=[@"1" boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]} context:nil].size;
    
    
    return size;
}


//将按钮设置为图片在上，文字在下
-(void)initButton{
    float  spacing = 2;//图片和文字的上下间距
    CGSize imageSize = self.imageView.frame.size;
    CGSize titleSize = self.titleLabel.frame.size;
    CGSize textSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : self.titleLabel.font}];
    CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
    if (titleSize.width + 0.5 < frameSize.width) {
        titleSize.width = frameSize.width;
    }
    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
    self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, - imageSize.width, - (totalHeight - titleSize.height), 0);
    
}
@end
